/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package imat;

import java.awt.Dimension;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import javax.swing.JPanel;
import se.chalmers.ait.dat215.project.Product;

/**
 *
 * @author Andreas
 */
public class ProductListPresenter {

    private ProductListView productListView;

    public ProductListPresenter(ProductListView view) {
        productListView = view;
    }

    public void setCategory(CategoryName catHandler) {
        Category c = DataHandler.getInstance().getCategory(catHandler);
        List<Product> products = c.getProducts();
        System.out.println(catHandler);
        productListView.getProductsPanel().removeAll();
        Product[] pr = new Product[c.getProducts().size()];
        pr = products.toArray(pr);

        Arrays.sort(pr, new Comparator<Product>() {

            public int compare(Product o1, Product o2) {
                if (DataHandler.getInstance().isFavorite(o1)) {
                    return -1;
                }
                else if (DataHandler.getInstance().isFavorite(o2)) {
                    return 1;
                }
                return 0;
            }
        });

        for (Product p : pr) {
            addProduct(p);
        }

        int cap = c.getProducts().size();
        JPanel panel = productListView.getScrollPanel();

        int w = panel.getSize().width;
        int nrW = 1;
        if (w >= 795)
            nrW = 3;
        else if (w >= 530)
            nrW = 2;
        int rows = (cap / nrW) + 1;
        panel.setPreferredSize(new Dimension(0, 10+rows*130));
        panel.revalidate();

        productListView.repaint();
        productListView.getCategoryTitle().setText(c.getLabel());
    }

    public void addProduct(Product p) {
        ProductView view = new ProductView();
        view.setProduct(p);
        productListView.getProductsPanel().add(view);
        productListView.validate();
    }

    public void clearPanel() {
        productListView.getProductsPanel().removeAll();
        productListView.repaint();
        productListView.getCategoryTitle().setText("");
    }

}
